package com.example.config;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.domain.User;
import com.example.result.EmployeeResult;
import com.example.result.JsonResult;
import com.example.untils.BaseContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class loginEmployeeIntercetor implements HandlerInterceptor {
    //目标方法执行之前 执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //判断session是否存在empolyee
        EmployeeResult employeeResult =(EmployeeResult)request.getSession().getAttribute("employee");
        //判断session是否存在User
        User user =(User)request.getSession().getAttribute("user");
        if(employeeResult!=null){
            if(user==null&&requestURI.contains("/front")){
                response.sendRedirect("/front/page/login.html");
            }
            //存入TreadLocal,以便进行公共字段填充
            BaseContext.setCurrentId(employeeResult.getId());
            return true;    //表示放行
        }
        if(user!=null){
            if(employeeResult==null&&requestURI.contains("/backend")){
                response.sendRedirect("/backend/page/login/login.html");
            }
            //存入TreadLocal,以便进行公共字段填充
            BaseContext.setCurrentId(user.getId());
            return true;
        }

        if(requestURI.contains("/backend")){
            response.sendRedirect("/backend/page/login/login.html");
        }
        if(requestURI.contains("/front")){
            response.sendRedirect("/front/page/login.html");
        }
        return false;     //表示不放行
    }
    //在目标方法执行之后 视图对象返回之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //在流程都执行完毕后  执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}